package com.midian.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.midian.common.exception.BizException;
import com.midian.common.system.SysStatic;
import com.midian.model.common.FileModel;

/**
 * 
 * @Title:TODO  
 * @Desription:文件上传的帮助类 FileUpload
 * @Company:MDKG
 * @ClassName:FileUpload.java
 * @Author:Mengfh
 * @CreateDate:2013-6-7 下午5:01:34  
 * @UpdateUser:Mengfh 
 * @Version:0.1
 */
public class FileUploadUtil {
	/**
	 * 
	 * @ClassName: FileUpload.java
	 * @Description: 上传文件
	 * @Author:Mengfh
	 * @CreateDate:2013-6-7 下午5:01:55
	 * @param fileModel 文件模型
	 * @param path 保存文件路径,默认/为项目的根目录
	 * @param fileName 保存文件名称
	 * @return 上传文件并返回文件类型
	 * @throws BizException
	 */
	public static String uploadFile(FileModel fileModel,String path) throws BizException {
		//获取项目真实路径
		String realPath = SysStatic.FILE_ROOT_PATH;
		System.out.println("开始上传文件:"+realPath);
		String fileType="";
		if (fileModel==null||StringUtils.isBlank(fileModel.getFileFileName())) {
			return null;
		}
		BufferedInputStream bs = null;
		BufferedOutputStream bos = null;
		// 获取文件后缀
		String file = fileModel.getFileFileName();
		fileType = file.substring(file.lastIndexOf("."));
		String fileName=String.valueOf(new Date().getTime());
		fileName = fileName + fileType.toLowerCase();//文件名小写处理
		try {
			File pathFile = new File(realPath+path);
			if(!pathFile.exists()||!pathFile.isDirectory()){
				pathFile.mkdirs();
			}
			//System.out.println("上传文件的保存路径为:"+pathFile);
			InputStream in = new FileInputStream(fileModel.getFile());
			OutputStream out = new FileOutputStream(new File(realPath+path, fileName));
			bs = new BufferedInputStream(in);
			bos = new BufferedOutputStream(out);
			int read = -1;
			byte[] buffer = new byte[2048];
			while ((read = bs.read(buffer)) != -1) {
				bos.write(buffer);
				bos.flush();
			}
		}catch (IOException e) {
			e.printStackTrace();
			throw new BizException("保存文件失败!");
		}finally {
			if (bs != null) {
				try {
					bs.close();
				} catch (IOException e) {
					//e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					//e.printStackTrace();
				}
			}
		}
		if(!path.endsWith("/")) {
			path += "/";
		}
		return path+fileName;
	}
	
	/***
	 * 生成html文件
	 * @param savePath 保存路径相对    
	 * @param saveName 保存文件名称
	 * @param vavalueList 文件内容
	 * @throws BizException 
	 */
	public static void writHtml(String savePath,String saveName,List<String> valueList) throws BizException{
		  String resourcePath = FileUploadUtil.class.getResource("/").getPath();
	        String folderPath  = resourcePath.replace("WEB-INF/classes/", "");
	        //"/mc/reportHTML/"
	        String dirPath=folderPath+savePath;
	        //System.out.println(dirPath);
	        File file = new File(dirPath);
	        if(!file.exists()){
	        	file.mkdir();
	        }
	       
	        OutputStreamWriter write= null;

	        BufferedWriter  bw=null;
			try {
					write =new OutputStreamWriter(new FileOutputStream(new File(dirPath+saveName)),"utf-8");//();
				    bw=new BufferedWriter(write);
				    bw.write("<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>");
				    bw.write("<html>");
				    bw.write("<head>");
				    bw.write("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
 				    bw.write("</head>");
				    bw.write("<body>");
				    
				 for (String strHtml : valueList) {
					// //System.out.println(strHtml);
					 bw.write(strHtml);
					 bw.write("\n");
				}
				  bw.write("</body>");
				 bw.write("</html>");
				 bw.flush();
				 bw.close();
				 write.close();
			} catch (IOException e) {
				 //e.printStackTrace();
				throw new BizException("生成html文件失败");
			}finally{
				if(bw!=null){
					try {
						bw.close();
					} catch (IOException e) {
						 //e.printStackTrace();
					}
				}
				if(write!=null){
					try {
						write.close();
					} catch (IOException e) {
						 //e.printStackTrace();
					}
				}
			}
	}
	/**
	 * 递归删除文件包括最外层文件夹
	 * @param file 目标文件
	 */
	public static void deleteFiles(File file){
		if(file.exists()){
			if(file.isFile()){
				boolean result = file.delete();
				System.out.println(result);
			}else{
				File[] listFiles = file.listFiles();
				for(File f :listFiles){
					if(f.isFile()){
						f.delete();
					} else {
						deleteFiles(f);
					}
				}
				file.delete();
		   }
	    }
	}
}
